import { effect, EffectType } from './effect.js'

// 代理映射表
const proxyMap = new WeakMap()

export function reactive(target) {
  // 不是对象无法拦截
  if (target === null || typeof target !== 'object') {
    return target
  }

  // 不需要重复代理
  if (proxyMap.get(target)) {
    return proxyMap.get(target)
  }

  const proxy = new Proxy(target, {
    get(target, key, receiver) {
      effect(target, EffectType.GET, key)
      return Reflect.get(target, key, receiver)
    },
    set(target, key, value, receiver) {
      effect(target, EffectType.SET, key)
      return Reflect.set(target, key, value, receiver)
    },
    has(target, key) {
      effect(target, EffectType.HAS, key)
      return Reflect.has(target, key)
    },
    deleteProperty(target, key) {
      effect(target, EffectType.DELETE, key)
      return Reflect.deleteProperty(target, key)
    },
    ownKeys(target) {
      effect(target, EffectType.ITERATOR)
      return Reflect.ownKeys(target)
    }
  })

  proxyMap.set(target, proxy)
  return proxy
}